package cn.z2huo.demo.jakarta.validation.annotation.validator;

import cn.z2huo.demo.jakarta.validation.annotation.InStringList;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.apache.commons.lang3.StringUtils;

import java.util.Set;

/**
 * <p>
 *
 * @author z2huo
 */
public class InStringListConstraintValidator implements ConstraintValidator<InStringList, Object> {

    private Set<String> stringSet;

    @Override
    public void initialize(InStringList constraintAnnotation) {
        stringSet = Set.of(constraintAnnotation.values());
    }

    @Override
    public boolean isValid(Object verifiedValue, ConstraintValidatorContext context) {
        if (verifiedValue == null) {
            return true;
        }
        boolean isValue = false;
        if (verifiedValue instanceof String) {
            String stringValue = String.valueOf(verifiedValue);
            if (StringUtils.isNotBlank(stringValue)) {
                // 如果待验证字符串不为空，且在注解List中，则通过验证
                isValue = stringSet.contains(stringValue);
            } else {
                // 如果待验证字符串为空，则直接通过验证
                isValue = true;
            }
        }
        return isValue;
    }
}
